package com.dg.river.core.view;


import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;


import com.dg.river.R;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by 刘超
 * on 2020/3/29 9:39
 * 自定义viewgroup
 */
public class TextFlowLayout extends ViewGroup {

    public static final float DEFAULT_SPACE = 10;
    private float mItemHorizontalSpace = DEFAULT_SPACE;
    private float mItemVerticalSpace = DEFAULT_SPACE;
    private int selfWith;
    private int mItemHeight;
    private OnFlowTextItemClickLiseter textItemClickListener = null;

    public int getContentSize(){
        return mTextList.size();
    }


    public float getmItemHorizontalSpace() {
        return mItemHorizontalSpace;
    }

    public void setmItemHorizontalSpace(float mItemHorizontalSpace) {
        this.mItemHorizontalSpace = mItemHorizontalSpace;
    }

    public float getmItemVerticalSpace() {
        return mItemVerticalSpace;
    }

    public void setmItemVerticalSpace(float mItemVerticalSpace) {
        this.mItemVerticalSpace = mItemVerticalSpace;
    }

    private List<String> mTextList = new ArrayList<>();

    //使用this 统一入口 不光那个构造方法 都进统一的入口
    public TextFlowLayout(Context context) {
        this(context,null);
    }

    public TextFlowLayout(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public TextFlowLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr,defStyleAttr);
        //去拿到相关属性
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.FlowTextStyle);
        //自定义属性
        mItemHorizontalSpace = typedArray.getDimension(R.styleable.FlowTextStyle_horizontalSpace, DEFAULT_SPACE);
        mItemVerticalSpace = typedArray.getDimension(R.styleable.FlowTextStyle_verticalSpace, DEFAULT_SPACE);
        //释放回收
        typedArray.recycle();
    }

    /**
     * 负责接收数据
     * @param textList
     */
    public void setTextList(List<String> textList){
        removeAllViews();
        this.mTextList.clear();
        this.mTextList.addAll(textList);
        Collections.reverse(mTextList);
        //遍历内容
        for (String text : textList) {
            //添加子view
            //LayoutInflater.from(getContext()).inflate(R.layout.flow_text_view,this,true);
            //等价于
            TextView item = (TextView) LayoutInflater.from(getContext()).inflate(R.layout.flow_text_view,this,false);
            item.setText(text);
            item.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    textItemClickListener.onFlowItemClick(text);
                }
            });
            addView(item);
        }
    }


    //这个是描述所有的行
    private List<List<View>> lines = new ArrayList<>();

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //当数据加载慢 数据没有回来时
        if (getChildCount() == 0){
            return;
        }
        //这个是描述单行
        List<View> line = null;
        lines.clear();
        //获取控件在屏幕中的宽度
        selfWith = MeasureSpec.getSize(widthMeasureSpec) - getPaddingLeft() - getPaddingRight();
        //对view的测量
        //测量子View
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            View itemView = getChildAt(i);
            if (itemView.getVisibility() != VISIBLE){
                //不进行测量
                continue;
            }
            //测量前
            measureChild(itemView,widthMeasureSpec,heightMeasureSpec);
            //测量后
            if (line == null) {
                //说明当前行为空，可以添加进来
                line = createNewLine(itemView);
            }else{
                //判断是否可以再继续添加
                if (canBeAdd(itemView,line)) {
                    //可以添加进去
                    line.add(itemView);
                }else {
                    //新创建一行
                    line = createNewLine(itemView);
                }
            }
        }
        mItemHeight = getChildAt(0).getMeasuredHeight();
        int selfHight = (int) (lines.size() * mItemHeight  + mItemVerticalSpace * (lines.size()+1) + 0.5f);
        //测量自己
        setMeasuredDimension(selfWith,selfHight);
    }

    private List<View> createNewLine(View itemView) {
        List<View> line = new ArrayList<>();
        line.add(itemView);
        lines.add(line);
        return line;
    }

    /**
     * 判断当前行是否可以再继续添加数据
     * @param itemView
     * @param line
     */
    private boolean canBeAdd(View itemView, List<View> line) {
        //所有已经添加的子View宽度相加+ (line.size()+1)+  mItemHorizontalSpace + itemVew.getMeasureWith()
        //条件：如果小于或等于当前控件的宽度，则可以添加，否则不能添加
        int totalWith = itemView.getMeasuredWidth();
        for (View view : line) {
            //添加所有已经添加控件的宽度
            totalWith += view.getMeasuredWidth();
        }
        //水平艰巨的宽度
        totalWith += mItemHorizontalSpace * (line.size() + 1);

        //条件：如果小于或等于当前控件的宽度，则可以添加，否则不能添加

        return totalWith <= selfWith;


    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int topOffSet = (int)mItemHorizontalSpace;
        //摆放子view
        for (List<View> views : lines) {
            //views是每一行
            int leftOffSet = (int)mItemHorizontalSpace;

            for (View view : views) {
                //每一行中的view
                view.layout(leftOffSet,topOffSet,leftOffSet + view.getMeasuredWidth(),topOffSet + view.getMeasuredHeight());
                //
                leftOffSet += view.getMeasuredWidth() + mItemHorizontalSpace;
            }
            topOffSet += mItemHeight +mItemHorizontalSpace;
        }
    }

    public void setOnFlowTextItemClickLiseter(OnFlowTextItemClickLiseter  liseter){
        this.textItemClickListener = liseter;
    }

    public interface OnFlowTextItemClickLiseter{
        void onFlowItemClick(String text);
    }
}
